#include "../include/EchoServer.h"

extern double Accurate;
extern double Searched;


void MyTask::process() {
    if (2 == _msgid) {

        //1.未添加连接池版
        //WebPageSearcher search(_msg)
        //vector<string> answer;
        //search.doQuery(jieba,string("tcp://127.0.0.1:6379"),answer);
        // ser_msg msg{200,answer};
        // json send_json;
        // ser_to_json(send_json,msg);
        // str_result=send_json.dump();
        // _con->sendInLoop(str_result);

        //2.添加连接池版
        WebPageSearcher testWeb(_msg);
        SplitToolCppJieba jieba(Configuration::getInstance());
        testWeb.doQuery(jieba);

        _con->sendInLoop(testWeb._str_result);
    }

    // WebPageSearcher web1(_msg);
    // web1.doQuery();
    // string sret=web1.str_result;}

    if (1 == _msgid) {
        shared_ptr<CacheManager> caches =
        Singleton<CacheManager>::GetInstance(4, 64);

        //线程局部存储
        LRUCache* p1 = caches->getcache(name);
        
        std::pair<std::string, std::vector<std::string>> res;

        if (p1->get(_msg, res) == -1) {
            string tmp = "缓存未命中 , 命中率为：";
            Searched++;
            string ac = to_string(Accurate/Searched);
            string ss = "\033[31m" + tmp + ac + "\033[0m";
            cout << ss << endl;

            cout <<"尝试通过字典和索引获取推荐的关键词"<<endl;

            KeyRecommander key(_msg);
            //cout << "1"<<endl;

            //尝试获取推荐的关键词，通过字典和索引
            res.second = key.execute();
            //cout << "2"<<endl;

            //查询到有结果 LRUCache缓存会有动作
            if(!res.second.empty())
            {   
                cout <<"成功通过字典和索引获取推荐,开始将结果存入RUL缓存"<<endl;
                p1->put(_msg, res.second);
                cout <<"结果成功存入RUL缓存"<<endl;
            }
            //p1->put(_msg, res.second);
        } else {
            
            string tmp = "缓存命中! ! 命中率为：";
            Searched++;
            Accurate++;
            string ac = to_string(Accurate/Searched);
            string ss = "\033[32m" + tmp + ac + "\033[0m";
            cout << ss << endl;
        }

        cout<<"用json打包推荐的关键词"<<endl;
        vector<string> s1 = res.second;
        json j1{{"msgid", 100}, {"data", s1}};
        string s2 = j1.dump();

        cout<<"json打包推荐的关键词完成"<<endl;
        _con->sendInLoop(s2);
        cout<<"json打包推荐的关键词完成,已经由TcpConnectionPtr发回EventLoop"<<endl;

    }
    // vector<string> s1=k1.execute();

    // string sret=k1.a()}

    //_con->sendInLoop(_msg);
}